<template>
  <transition name="el-fade-in">
    <div class="root-container" v-if="routeData && showContent">
      <el-row :gutter="24">
        <el-col :sm="24" :md="12">
          <Graphic :route="currentRoute.route" :selected="currentSelected" />
        </el-col>
        <el-col :sm="24" :md="12">
          <div class="question-area base-container" v-if="currentRight != ''">
            <div class="route">
              <span>{{ currentRoute.title }}: </span>
              <span v-for="item in currentSelected">{{ item }}</span>
            </div>
            <div class="question">
              <span>请选择</span>
              <span style="padding: 0 4px; font-weight: bold">
                {{ currentRoute.airport }}
              </span>
              <span style="font-weight: bold">
                {{ currentRoute.runway }}
              </span>
              <span>跑道</span>
              <span style="padding: 0 4px; font-weight: bold">
                {{ currentRoute.title }}
              </span>
              <span class="tag" v-if="currentRoute.attrib != ''">
                {{ currentRoute.attrib }}
              </span>
              <span>
                的第{{
                  currentSelected.length + (isCurrentSelectedWrong ? 0 : 1)
                }}个点：
              </span>
            </div>
            <div class="container-option-btn">
              <el-button
                v-for="item in currentOptions"
                :type="isLastWrong(item) ? 'danger' : 'primary'"
                @click="handleSelect(item)"
                class="option-btn"
                size="large"
              >
                {{ item }}
              </el-button>
            </div>
          </div>
          <div class="success-area base-container" v-else>
            <el-result icon="success" title="已完成">
              <template #extra>
                <el-button
                  class="next-btn"
                  type="success"
                  size="large"
                  @click="forward()"
                  >下一题</el-button
                >
              </template>
            </el-result>
          </div>
        </el-col>
      </el-row>
      <!-- <div class="footer">
      <el-button link @click="forward()">Next</el-button>
      <el-button link @click="backward()">Prev</el-button>
    </div> -->
    </div>
  </transition>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";

import graphicData from "./graphicData.json";
import generateRandomSequence from "@/utils/generateRandomSequence.js";
import shuffleArray from "@/utils/shuffleArray.js";
import routeDataRaw from "./routeData.json";
import Graphic from "./Graphic.vue";

const emits = defineEmits(["back"]);

const props = defineProps({
  filter: {
    type: Object,
    required: false,
    default: null,
  },
});

// const sequence = ref([]);
const pointer = ref(0);

const showContent = ref(true);

const routeData = ref();

const currentRoute = computed(() => {
  return routeData.value[pointer.value];
});

const currentSelected = ref([]);

const isCurrentSelectedWrong = ref(false);

const isLastWrong = (val) => {
  if (!val) return false;
  if (currentSelected.value.length == 0) return false;
  if (val == currentSelected.value[currentSelected.value.length - 1]) {
    if (val != currentRoute.value.route[currentSelected.value.length - 1])
      return true;
  }
  return false;
};

const handleSelect = (val) => {
  // 判断对错
  if (currentRight.value != "" && val != currentRight.value) {
    isCurrentSelectedWrong.value = true;
    // console.log("选择了", val, "选错了");
  } else {
    isCurrentSelectedWrong.value = false;
    // console.log("选择了", val, "选对了");
  }
  // 操作数组
  if (currentSelected.value.length == 0) {
    // console.log("handleSelect", "1. 新的题目第一次选择");
    currentSelected.value.push(val);
  } else if (currentSelected.value.length == currentRoute.value.route.length) {
    // console.log("handleSelect", "2. 作答数组长度已经足够，本次覆盖上一次作答");
    currentSelected.value[currentSelected.value.length - 1] = val;
  } else if (
    currentSelected.value[currentSelected.value.length - 1] !=
    currentRoute.value.route[currentSelected.value.length - 1]
  ) {
    // console.log("handleSelect", "3. 最后一次作答不正确，本次覆盖上一次作答");
    currentSelected.value[currentSelected.value.length - 1] = val;
  } else {
    // console.log("handleSelect", "4. 最后一次作答正确，答案数组长度不够，继续");
    currentSelected.value.push(val);
  }
  // console.log("currentSelected", currentSelected.value);

  // 生成新的选项数组
  if (isCurrentSelectedWrong.value == false) {
    getCurrentOptions();
  }
};

const currentRight = computed(() => {
  if (currentSelected.value.length == currentRoute.value.route.length) {
    // 已选择的长度和正确答案长度一致
    if (
      currentSelected.value[currentSelected.value.length - 1] ==
      currentRoute.value.route[currentRoute.value.route.length - 1]
    ) {
      // 最后一个选项正确
      return "";
    } else {
      // 否则
      return currentRoute.value.route[currentRoute.value.route.length - 1];
    }
  }
  if (
    currentSelected.value[currentSelected.value.length - 1] ==
    currentRoute.value.route[currentSelected.value.length - 1]
  ) {
    // 最后一个选项正确，返回下一个正确答案
    return currentRoute.value.route[currentSelected.value.length];
  } else {
    // 最后一个选项不正确，返回当前正确答案
    // return currentRoute.value.route[currentRoute.value.route.length - 1];
    return currentRoute.value.route[currentSelected.value.length - 1];
  }
});

const optionCount = 4;

const currentOptions = ref([]);
const showOptions = ref(true);

const getCurrentOptions = async () => {
  showOptions.value = false;
  const options = [];
  if (!currentRight.value || currentRight.value === "") {
    return options;
  } else {
    let allPoints = Object.keys(graphicData.points);
    let similarPoints = allPoints.filter(
      (p) =>
        p.includes(currentRight.value.substring(0, 3)) &&
        p !== currentRight.value &&
        !currentSelected.value.includes(p)
    );
    options.push(currentRight.value);
    if (similarPoints.length === optionCount - 1) {
      // 1. similarPoints 长度恰好
      options.push(...similarPoints);
    } else if (similarPoints.length >= optionCount) {
      // 2. similarPoints 长度大于 optionCount
      options.push(
        ...generateRandomSequence(similarPoints.length, optionCount - 1).map(
          (i) => similarPoints[i]
        )
      );
    } else {
      // 2. similarPoints 长度小于 optionCount
      options.push(
        ...similarPoints,
        ...generateRandomSequence(
          allPoints.length,
          optionCount - 1 - similarPoints.length
        ).map((i) => allPoints[i])
      );
    }

    currentOptions.value = shuffleArray(options);
    await nextTick();
    showOptions.value = true;
    // console.log("生成新的选项数组", currentOptions.value);
    return currentOptions.value;
  }
};

const forward = async () => {
  showContent.value = false;
  currentSelected.value = [];
  if (pointer.value < routeData.value.length - 1) {
    pointer.value++;
  } else {
    pointer.value = 0;
    ElNotification.info({
      title: "已完成全部题目",
      message: "已经跳转至跳转至第一题",
      duration: 2000,
    });
  }
  getCurrentOptions();
  await nextTick();
  showContent.value = true;
  // console.log("forward", pointer.value, routeData.value.length);
  // console.log("currentRoute", currentRoute.value);
};
const backward = async () => {
  showContent.value = false;
  currentSelected.value = [];
  if (pointer.value > 0) {
    pointer.value--;
  } else {
    pointer.value = routeData.value.length - 1;
    ElNotification.info({
      title: "到头了",
      message: "已经跳转至跳转至最后一题",
      duration: 2000,
    });
  }
  getCurrentOptions();
  await nextTick();
  showContent.value = true;
  // console.log("backward", pointer.value, routeData.value.length);
  // console.log("currentRoute", currentRoute.value);
};

onMounted(() => {
  if (props.filter) {
    routeData.value = shuffleArray(
      routeDataRaw.filter(
        (r) =>
          props.filter.airport.includes(r.airport) &&
          props.filter.type.includes(r.type) &&
          (props.filter.direction.includes(r.direction) ||
            r.direction == "*") &&
          props.filter.attrib.includes(r.attrib)
      )
    );
  } else {
    routeData.value = shuffleArray(routeData.value);
  }

  if (routeData.value.length == 0) {
    ElNotification.error("没有符合条件的航线数据！");
    emits("back");
    return;
  }

  getCurrentOptions();
  // console.log(
  //   "List:",
  //   routeData.value
  //     .map((r) => `${r.airport}, ${r.runway}, ${r.title}`)
  //     .join("\n")
  // );
  // sequence.value = generateRandomSequence(routeData.value.length);
});
</script>

<style scoped>
@import "./container.css";

.root-container {
  /* min-height: 100vh; */
  min-width: 100vw;
}

.footer {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.question-area {
  margin: 10px;
}

.question {
  text-align: justify;
  padding: 6px 12px;
  color: var(--el-color-info);
  line-height: 24px;
}

.route {
  font-size: 12px;
  color: var(--el-color-info);
  text-align: justify;
  padding: 6px 12px;
}

.route > * {
  margin-right: 8px;
  border-bottom: 1px solid var(--el-color-info);
}

.route > *:first-child {
  border: none;
  font-weight: bold;
}

.route > *:last-child {
  margin-right: 0;
}

.tag {
  border-radius: 8px;
  font-size: 12px;
  border: 1px solid var(--el-color-info-light-3);
  background-color: var(--el-color-info-light-7);
  margin: 0 4px;
  color: var(--el-color-info);
  padding: 3px 4px;
}

.container-option-btn {
  width: 100%;
  padding: 6px 12px 6px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
}

.option-btn {
  /* max-width: 120px; */
  min-width: 100px;
  min-height: 60px;
  width: calc(50% - 36px);
  font-size: 1.5em;
  font-weight: bold;
  margin: 12px !important;
  border-radius: 12px;
}

.next-btn {
  min-width: 120px;
  max-width: 360px;
  min-height: 50px;
  width: calc(100% - 36px);
  font-size: 1.2em;
  font-weight: bold;
  margin: 12px !important;
  border-radius: 12px;
}
</style>
